package com.tianxinweb.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.tianxinweb.entity.Result;
import com.tianxinweb.entity.User;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import com.tianxinweb.service.UserService;
import com.tianxinweb.utils.CommonUtil;
import com.tianxinweb.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cboy
 * @since 2018-08-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;
	
    /**
     * 用户登录
     * @param user
     * @param result
     * @param session
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody @Valid User user, BindingResult result, HttpSession session){

        //参数错误
        if(result.hasErrors() || !user.getLoginPwd().equals(user.getConfirmPwd())){
            throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        }

        String code = (String) session.getAttribute(user.getTelphone());
        //验证码已过期,需重新获取
        if(code==null) throw new MyException(ResultEnum.CHECKCODE_EXPIRED);

        //session中的验证码只能用一次
        session.removeAttribute(user.getTelphone());

        //验证码错误
        if(!code.equals(user.getCheckcode())){
            throw new MyException(ResultEnum.CHECKCODE_ERROR);
        }

        User dbUser = service.getUserByPhone(user.getTelphone());
        if(dbUser==null){//数据库未存在该用户
            //保存用户
            service.addUser(user);
        }else{//数据库已存在该用户
            throw new MyException(ResultEnum.THE_PHONE_IS_USED);
        }

        return  Result.success();
    }

    /**
     * 后台添加用户
     * @param user
     * @param result
     * @return
     */
    @RequestMapping("addUser")
    public Result addUser(@RequestBody @Valid User user, BindingResult result){

        //参数错误
        if(result.hasErrors() || !user.getLoginPwd().equals(user.getConfirmPwd())){
            throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        }
        User dbUser = service.getUserByPhone(user.getTelphone());
        if(dbUser==null){//数据库未存在该用户
            //保存用户
            service.addUser(user);
        }else{//数据库已存在该用户
            throw new MyException(ResultEnum.THE_PHONE_IS_USED);
        }

        return  Result.success();
    }

    @RequestMapping("updateUser")
    public Result updateUser(@RequestBody @Valid User user, BindingResult result){

        //参数错误
        if(result.hasErrors() || user.getUid()==null){
            throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        }
        User dbUser = service.getUserByPhone(user.getTelphone());
        if(dbUser != null && dbUser.getUid()!=user.getUid()){
            throw new MyException(ResultEnum.THE_PHONE_IS_USED);
        }
        //保存用户
        service.updateUser(user);
        return  Result.success();
    }

    /**
     * 用户登录
     * @param account
     * @param pwd
     * @param session
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestParam("account") String account,@RequestParam("pwd") String pwd, HttpSession session){

        User user = service.getUserByPhoneOrUid(account);
        if(user==null) throw new MyException(ResultEnum.LOGIN_PWD_OR_ACCOUNT_ERROR);
        if(!user.getLoginPwd().equals(Md5Util.generate(pwd,user.getLoginSalt()))){
            throw new MyException(ResultEnum.LOGIN_PWD_OR_ACCOUNT_ERROR);
        }
        //判断用户是否已被禁用
        if(user.getUstatus()) throw new MyException(ResultEnum.ACCOUNT_LOCKED_UP);
        session.setAttribute("userId",user.getUid());
        return  Result.success();
    }

    /**
     * 用户注销登录
     * @param session
     * @return
     */
    @RequestMapping("logout")
    public Result logout(HttpSession session){
        session.removeAttribute("userId");
        return  Result.success();
    }

    /**
     * 获取用户信息
     * @param session
     * @return
     */
    @RequestMapping("getUserInfo")
    public Result getUserInfo(HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        User user = service.selectById(userId);
        return  Result.success().add("info",user);
    }

    /**
     * 修改用户头像
     * @param session
     * @return
     */
    @PostMapping("editUserImg")
    public Result editUserImg(@RequestParam("path") String path, HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        service.editUserImg(userId,path);
        return  Result.success();
    }

    /**
     * 修改用户登录密码
     * @param oldPwd
     * @param newPwd
     * @param confirmPwd
     * @param session
     * @return
     */
    @PostMapping("editLoginPwd")
    public Result editLoginPwd(@RequestParam("oldPwd") String oldPwd,
                          @RequestParam("newPwd") String newPwd,
                          @RequestParam("confirmPwd") String confirmPwd,
                          HttpSession session){
        if(!newPwd.equals(confirmPwd)) throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        Integer userId = (Integer) session.getAttribute("userId");
        service.editLoginPwd(userId,oldPwd,newPwd);
        return  Result.success();
    }

    /**
     * 修改支付密码
     * @param checkcode
     * @param newPwd
     * @param confirmPwd
     * @param session
     * @return
     */
    @PostMapping("editPayPwd")
    public Result editPwd(@RequestParam("checkcode") String checkcode,
                          @RequestParam("newPwd") String newPwd,
                          @RequestParam("confirmPwd") String confirmPwd,
                          HttpSession session){
        if(!newPwd.equals(confirmPwd)) throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        Integer userId = (Integer) session.getAttribute("userId");
        User user = service.selectById(userId);
        String code = (String) session.getAttribute(user.getTelphone());
        if(code==null) throw new MyException(ResultEnum.CHECKCODE_EXPIRED);
        if(!code.equals(checkcode)) throw new MyException(ResultEnum.CHECKCODE_ERROR);

        service.editPayPwd(user,newPwd);
        return  Result.success();
    }

    /**
     * 校验验证码是否正确
     * @param checkcode
     * @return
     */
    @RequestMapping("validCheckcode")
    public Result validCheckcode(@RequestParam("checkcode") String checkcode, HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        User user = service.selectById(userId);
        String code = (String) session.getAttribute(user.getTelphone());
        if(code != null && code.equals(checkcode)){
            if(code.equals(checkcode)){
                return Result.success();
            }else{
                session.removeAttribute(user.getTelphone());
                return Result.fail();
            }
        }else{
            return Result.fail();
        }
    }

    /**
     * 获取用户的直接下级列表
     * @param session
     * @return
     */
    @RequestMapping("getUserInvitationList")
    public Result getInvitationList(HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        List<User> list = service.getInvitationList(null,userId);
        return Result.success().add("list",list);
    }

    /**
     * 通过唯一码获取下级列表
     * @param uniqueCode
     * @return
     */
    @RequestMapping("getInvitationListByCode")
    public Result getInvitationList(@RequestParam(value = "uniqueCode") String uniqueCode){
        List<User> list = service.getInvitationList(uniqueCode,null);
        return Result.success().add("list",list);
    }

    /**
     * 管理员充值黑金币或种子币
     * @param uid
     * @param num
     * @param type 充值类型，默认为0表示黑金币，1表示种子币，2表示注册金，3表示购币金
     * @param session
     * @return
     */
    @PostMapping("recharge")
    public Result recharge(@RequestParam("uid") Integer uid,
                           @RequestParam(value = "num",required = false) Integer num,
                           @RequestParam(value = "type",defaultValue = "0") Integer type,
                           @RequestParam(value = "money",required = false) BigDecimal money,
                           HttpSession session){
        Integer adminId = (Integer) session.getAttribute("adminId");
        service.recharge(uid,adminId,num,type,money);
        return  Result.success();
    }

    /**
     * 搜索/获取用户列表
     * @param pn
     * @param size
     * @return
     */
    @RequestMapping("list")
    public Result list(@RequestParam(value="pn",defaultValue="1") Integer pn,
                       @RequestParam(value="size",defaultValue="10") Integer size,
                       @RequestParam(value = "key",defaultValue = "") String key) {
        Page page = service.getUserList(pn,size,key);
        return Result.success().add("page",page);
    }

    /**
     * 通过id获取详情
     * @param id
     * @return
     */
    @RequestMapping("getDetailById/{id}")
    public Result getInvitationList(@PathVariable("id") Integer id){
        User user = service.getUserDetail(id);
        return Result.success().add("detail",user);
    }

    /**
     * 根据id禁用用户
     * @param id
     * @return
     */
    @RequestMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id,@RequestParam(value = "type",defaultValue = "1") Integer type){
        User user = new User();
        user.setUid(id);
        if(type==1){
            user.setUstatus(true);
        }else{
            user.setUstatus(false);
        }
        service.updateById(user);
        return Result.success();
    }

    /**
     * 后台获取管理员关系列表
     * @param id，id为0表示获取最顶级用户列表
     * @return
     */
    @RequestMapping("getUserRelation/{id}")
    public Result getUserRelation(@PathVariable("id") Integer id){
        List<User> list = service.getUserRelation(id);
        return Result.success().add("list",list);
    }

    /**
     * 后台删除最下级用户关系（只能删除最下级的关系）
     * @param id
     * @return
     */
    @RequestMapping("deleteUserRelation/{id}")
    public Result deleteUserRelation(@PathVariable("id") Integer id){
        service.deleteUserRelation(id);
        return Result.success();
    }

}

